import requests


# 定义贴吧爬虫类
class TiebaSpider:
    # 初始化
    def __init__(self, tieba_name):
        # 声明贴吧名
        self.tieba_name = tieba_name
        # 贴吧初始地址
        self.url_temp = "https://tieba.baidu.com/f?kw=" + tieba_name + "&pn={}"
        # 请求信息
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"}

    # 构造url列表
    def get_url_list(self):
        # 列表推导式遍历 获得URL列表
        return [self.url_temp.format(i * 50) for i in range(1000)]

    # 发送请求获取响应
    def parse_url(self, url):
        response = requests.get(url, headers=self.headers)
        # 将获取到的代码格式化
        return response.content.decode()

    # 保存
    def save_html(self, html_str, page_num):
        # 定义 文件名与下载地址
        file_name = "{}-第{}页.html".format(self.tieba_name, page_num)
        print("正在保存{}".format(file_name))
        # 保存至文件夹
        with open( file_name, "w", encoding="utf-8")as f:
            f.write(html_str)

    # 定义运行函数
    def run(self):
        # 拿到URL列表
        url_list = self.get_url_list()
        # 循环遍历列表 将每个url依次请求
        for url in url_list:
            # 请求
            html_str = self.parse_url(url)
            # 拿到当前的页码
            page_num = url_list.index(url) + 1
            # 将拿到的html页面和页码创给save_html函数
            self.save_html(html_str, page_num)


if __name__ == '__main__':
    names = input("请输入要爬取的贴吧名：")
    tieba_spider = TiebaSpider(names)
    tieba_spider.run()
